package com.store.controller;

import com.store.entity.Cart;
import com.store.entity.Product;
import com.store.entity.SuperCart;
import com.store.mapper.CartMapper;
import com.store.service.ex.NotFindProductException;
import com.store.service.impl.CartServiceImpl;
import com.store.util.JsonResult;
import org.springframework.beans.NotReadablePropertyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cai
 * @since 2022-07-14
 */
@RestController
@RequestMapping("carts")
public class CartController extends BaseController{
    @Autowired
    CartServiceImpl cartService;
    @Autowired
    CartMapper cartMapper;

    @RequestMapping("add_to_cart")
    public JsonResult<Void> addCart(Integer pid, Integer amount, HttpSession session){
        //http://localhost:8082/carts/add_to_cart?pid=1000006&amount=33
        Integer  uid= getUidFromSession(session);
        String username=getUsernameFromSession(session);
        cartService.addCart(uid,pid,amount,username);
        return new JsonResult<Void>(OK);
        //return "OKKKK"+"/n"+pid+"/n"+amount+"/n"+getUidFromSession(session);
    }

    @RequestMapping({"","/"})
    public JsonResult<List<SuperCart>> getCartList(HttpSession session){
        List<SuperCart> data=cartService.getMyAllCart(getUidFromSession(session));
        return new JsonResult<>(OK,data);
    }

    @RequestMapping(value = {"{cid}/numAdd"},method = RequestMethod.POST,params = {"cid!=null"})
    public JsonResult<Integer> addNum(@PathVariable("cid") String cid){
        //http://localhost:8082/carts/13/numAdd
        Cart cart=cartMapper.selectById(cid);
        if (cart == null){
            throw new NotFindProductException("未发现cid");
        }
        cart.setNum(cart.getNum()+1);
        cartMapper.updateById(cart);
        return new JsonResult<Integer>(OK,cart.getNum());
    }


    @RequestMapping("list")
    public JsonResult<List<SuperCart>> getCartListToPay(Integer[] cids,HttpSession session){
        List<SuperCart> data=cartService.getSuperCartByCids(getUidFromSession(session),cids);
        return new JsonResult<>(OK,data);
    }
}
